<template>
  <div class="coachFrmPage">
    <div class="layoutCon">
      <div class="topInfo">
        <div class="info">
          <p class="tit"><b>신청하기</b>{{getTit()}}</p>
          <p class="tips"><b>신청서 작성</b>(※ 아래 내용을 확인하시고, 꼼꼼히 작성해주세요.)</p>
        </div>
        <div class="steps">
          <ul>
            <li class="active">신청대기</li>
            <li>임시저장</li>
            <li>신청완료</li>
            <li>코칭완료</li>
          </ul>
        </div>
      </div>
      <el-form class="frm" :model="frm" :rules="rules" ref="coachFrm" label-position="top">
      <div class="comTit">기본정보<span><i>*</i>필수입력사항</span></div>
      <el-form-item label="이름" prop="user_name" class="x">
        <el-col :span="14" :xs="12">
          <el-input v-model="frm.user_name"></el-input>
        </el-col>
        <el-col :span="10" :xs="12">
          <el-radio-group v-model="frm.sex">
              <el-radio-button label="1">남자</el-radio-button>
              <el-radio-button label="2">여자</el-radio-button>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label="휴대폰번호" prop="phone" class="x">
          <el-input placeholder="010-123-1234" v-model="frm.phone"></el-input>
      </el-form-item>
      <el-form-item label="이메일" prop="email" class="x">
          <el-input placeholder="example@workwiz.com" v-model="frm.email"></el-input>
      </el-form-item>
      <el-form-item :error="errors.upload" label="이력서 첨부하기" class="xl" prop="resume">
          <el-col :span="19" :xs="15" class="fileInp">
            <input type="hidden" v-model="frm.resume">
            <input type="file" title="" ref="fileInput" class="file" @change="changeFile">
            <el-input placeholder="파일을 첨부해주세요" v-model="fileName"></el-input>
          </el-col>
          <el-col :span="5" :xs="9">
            <el-button :loading="uploading" class="minBtn" plain @click="changeFileByInput">찾아보기</el-button>
          </el-col>
      </el-form-item>
      <div class="comTit">신청정보</div>
      <div class="list">
        <div class="proBox" v-for="(item,index) in frm.answers" :key="item.index">
          <el-form-item :prop="`answers.${index}.content`"
            :rules="{required: item.required, message: '내용을 작성해 주세요.', trigger: 'blur'}"
          >
            <div class="q" v-html="formatTit(questions[index].title)"></div>
            <div class="a">
              <el-input type="textarea" v-model="item.content" :rows="2" :placeholder="formatTit(questions[index].title)"></el-input>
            </div>
          </el-form-item>
        </div>
      </div>
      <el-form-item class="btns">
          <el-button :loading="loading" type="primary" class="subBtn" @click="save">신청완료</el-button>
          <el-button :loading="loading2" @click="saveDraft" class="plain">임시저장</el-button>
          <el-button @click="escFrm" class="plain">신청취소</el-button>
      </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { createService, coachQuestions, uploadFile } from '@/api'

export default {
  name:'',
  components:{ },
  props:[],
  data(){
    var validateMobile = (rule, value, callback) => {
      if (value==='') {
        callback(new Error('휴대폰번호를 입력해 주세요.'));
      } else if(!value.match( /^[0-9]{3}[0-9]{4}[0-9]{4}$/ )) {
        callback(new Error('정상적인 전화번호를 입력해주세요.'));
      }else{
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (value==='') {
        callback(new Error('아이디를 입력해 주세요.'));
      } else if(!value.match(/^[a-zA-Z0-9_-|.]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)) {
        callback(new Error('정확한 이메일 주소를 입력하세요.'));
      }else{
        callback();
      }
    };    
    return {
      uploading:false,
      loading:false,
      loading2:false,
      file:null,
      fileName:'',
      errors:{
        upload:'',
      },
      type:0,
      frm:{
        order_id:'',
        user_name:'',
        sex:1,
        phone:'',
        email:'',
        resume:'',
        answers:[],
        edit_status:0,
      },
      rules:{
        name: [
            { required: true, message: '이름을 입력해주세요.', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: 'change' }
        ],
        resume: [
            { required: true, message: '이력서를 첨부해 주세요.', trigger: 'change' }
        ]        
      },
      questions:[]
    }
  },
  computed:{
    ...mapState(['userInfo'])
  },
  created(){
    if(this.userInfo){
      this.frm.user_name=this.userInfo.name;
      this.frm.sex=this.userInfo.sex;
      this.frm.phone=this.userInfo.phone;
      this.frm.email=this.userInfo.email;
    }
    this.frm.order_id=this.$route.query.id||'';
    this.type=this.$route.query.type||1;
    this.coachQuestions()
  },
  mounted(){
  },
  methods:{
    async coachQuestions() {
      let res = await coachQuestions({id:this.frm.order_id});
      if (res.code == 200) {
          this.questions=res.data;
          let _data=res.data,_new=[];
          _data.forEach(item => {
            _new.push({
              question_id:item.id,
              required:(item.required==1?true:false),
              content:(item.answers||'').replace(/\/n/g,'\n')
            })
          });
          this.frm.answers=_new
      }
    },
    getTit(){
      let _tit='',_type=parseInt(this.type);
      switch(_type){
        case 2: return '이력서 클리닉'; break;
        case 3: return '채용정보서칭'; break;
        case 4: return '모의 서류전형'; break;
        case 5: return '모의 면접'; break;
        default: return '취업상담'; break;
      }
    },
    formatTit(txt){
      return txt.replace(/\/n/g,'')
    },
    save(){
      this.frm.edit_status=2;
      this.submitForm();
    },
    saveDraft(){
      this.frm.edit_status=1;
      this.submitForm();
    },
    async createService(){
      let _frmParams={};
      _frmParams={
        order_id:this.frm.order_id,
        user_name:this.frm.user_name,
        sex:this.frm.sex,
        phone:this.frm.phone,
        email:this.frm.email,
        resume:'',
        answers:JSON.stringify(this.frm.answers),
        edit_status:this.frm.edit_status
      }
      this.frm.resume&&(_frmParams.resume=this.frm.resume)
      let res = await createService(_frmParams);        
        if (res.code == 200) {
          this.loading = false;
          this.loading2 = false;
          let _msg='신청이 정상적으로 완료되었습니다.';
          if(this.frm.edit_status==1){
            _msg='임시저장이 완료되었습니다.'
          }
          this.$alert(_msg, '알림', {
            confirmButtonText: '확인',
            callback: action => {
              this.goMyCoach();
            }
          });
        }else{
          this.loading = false;
          this.loading2 = false;
          this.$alert(res.message, '알림', {
            confirmButtonText: '확인'
          });
        }
    },
    submitForm() {
      let that=this;
      this.$refs['coachFrm'].validate((valid,error) => {
        if (valid) {
          if(that.frm.edit_status==2){
            this.$confirm('신청완료를 선택하시면 더 이상 수정이 불가합니다. 정말 진행하시겠습니까?', '알림', {
              confirmButtonText: '확인',
              cancelButtonText: '취소',
            }).then(() => {
              this.loading = true;
              this.createService()
            });
          }else{
            this.loading2 = true;
            this.createService();
          }
        } else {
          this.$alert('작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.', '알림', {
            confirmButtonText: '확인'
          });
          return false;
        }
      });
    },
    escFrm(){
      this.$confirm('신청취소 하시면, 기존에 작성된 내용이 모두 삭제됩니다. 정말 진행하시겠습니까?', '알림', {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
      }).then(() => {
        this.goMyCoach();
      });
    },
    goMyCoach(){
      this.$router.replace('/my/coach')
    },
    changeFileByInput(){
      this.$refs.fileInput.click()
    },
    changeFile(){
      let inputDOM = this.$refs.fileInput;
      let files = inputDOM.files;
       if(files && files[0]) {
         let size = Math.floor(files[0].size / 1024);
          if (size > 5*1024) {
            this.$alert('5MB이하의 이력서를 첨부해주세요.', '알림', {
              confirmButtonText: '확인'
            });
            return false
          }
          this.file = files[0];
          this.fileName=this.file.name;
          this.uploadFile();
       }
    },
    async uploadFile(){
      if(this.file==null){
        this.errors.upload='이력서를 첨부해 주세요.'
      }else{
        try {
          this.uploading=true;
          let res = await uploadFile({file:this.file});
          if (res.code == 200) {
            this.frm.resume=res.data.id;
            this.$refs.coachFrm.validateField('resume');
            this.uploading=false;
            this.errors.upload=''
          }else{
            this.uploading=false;
          }
        } catch (error) {
          this.uploading=false;
          this.errors.upload='이력서 첨부 실패하였습니다.'
        }        
      }
    }
  },
  watch:{}
}
</script>
<style lang="scss" scoped>
  @import "@/assets/styles/coach.scss";
</style>